<script setup>

// 搜索关键词
import {Delete, Edit, Lock, Message, Plus, Refresh, Search, User} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {get, post} from '@/net/index.js'
import {ElMessage, ElMessageBox} from "element-plus";

// 当前页数
const currentPage = ref(1);
// 每页多少条
const pageSize = ref(10);
// 共计多少条
const total = ref(0);
// 查询出来的数据
const dataList = ref([]);
// 存放当前选取的数据
const multipleSelection = ref([])
// 新增表单显示
const addDialog = ref(false);
// 修改表单显示
const editDialog = ref(false);
// 表单标签位置
const labelPosition = ref('top');
// 搜索关键词
const searchKeyword = reactive({
    interfaceId: '',
    interfaceName: '',
});
// 表单内数据
const createForm = reactive({
    id: '',
    interfaceName: '',
    interfaceDescription: '',
    interfaceUrl: '',
    interfacePath: '',
    interfaceRequestParams: '',
    interfaceRequestParamsDesc: '',
    interfaceReturnParamsDesc: '',
    interfaceJsonReturn: '',
    interfaceRequestHeader: '',
    interfaceResponseHeader: '',
    interfaceStatus: '',
    interfaceMethod: ''
});

// 新增接口
const handleAddConfirm = () => {
    post('/api/interfaceInfo/add',
        {
            name: createForm.interfaceName,
            description: createForm.interfaceDescription,
            url: createForm.interfaceUrl,
            path: createForm.interfacePath,
            requestParams: createForm.interfaceRequestParams,
            requestParamsDesc: createForm.interfaceRequestParamsDesc,
            returnParamsDesc: createForm.interfaceReturnParamsDesc,
            jsonReturn: createForm.interfaceJsonReturn,
            requestHeader: createForm.interfaceRequestHeader,
            responseHeader: createForm.interfaceResponseHeader,
            method: createForm.interfaceMethod,
        },
        () => {
            // 处理成功的情况
            ElMessage({
                message: "新增接口成功！",
                type: "success",
            })
            // 关闭表单窗口
            addDialog.value = false;
            // 清除表单上的数据
            cleanForm();
            // 刷新数据
            loadData(currentPage, pageSize)
        }
    )
};
// 关闭窗口处理
const dialogClose = () => {
    ElMessageBox.confirm('您有数据未保存，确定关闭窗口？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(() => {
            // 关闭窗口
            addDialog.value = false;
            editDialog.value = false
            // 清空表单中的数据
            cleanForm();
        })
        .catch(() => {
            // 不关闭窗口
        })
}
// 改变接口状态
const changeInterfaceStatus = (index, row) => {
    console.log(row.status)
    if(row.status === true) {
        post('/api/interfaceInfo/online',
            {
                id: row.id
            },
            () => {
                ElMessage({
                    message: "成功上线接口！",
                    type: "success",
                })
            }
        )
    } else {
        post('/api/interfaceInfo/offline',
            {
                id: row.id
            },
            () => {
                ElMessage({
                    message: "成功下线接口！",
                    type: "success",
                })
            }
        )
    }
};
// 编辑接口
const handleEditConfirm = () => {
    post('/api/interfaceInfo/update',
        {
            id: createForm.id,
            name: createForm.interfaceName,
            description: createForm.interfaceDescription,
            url: createForm.interfaceUrl,
            path: createForm.interfacePath,
            requestParams: createForm.interfaceRequestParams,
            requestParamsDesc: createForm.interfaceRequestParamsDesc,
            returnParamsDesc: createForm.interfaceReturnParamsDesc,
            jsonReturn: createForm.interfaceJsonReturn,
            requestHeader: createForm.interfaceRequestHeader,
            responseHeader: createForm.interfaceResponseHeader,
            method: createForm.interfaceMethod,
        },
        () => {
            // 处理成功的情况
            ElMessage({
                message: "编辑接口成功！",
                type: "success",
            })
            // 关闭表单窗口
            editDialog.value = false;
            // 清除表单上的数据
            cleanForm();
            // 刷新数据
            loadData(currentPage, pageSize)
        }
    );
};
// 点击编辑
const handleEdit = (index, row) => {

    get('/api/interfaceInfo/get/' + row.id,
        (data) => {
            // 显示编辑表单
            editDialog.value = true
            // 数据回显至表单
            createForm.id = data.id;
            createForm.interfaceName = data.name;
            createForm.interfaceDescription = data.description;
            createForm.interfaceUrl = data.url;
            createForm.interfacePath = data.path;
            createForm.interfaceRequestParams = data.requestParams;
            createForm.interfaceRequestParamsDesc = data.requestParamsDesc;
            createForm.interfaceReturnParamsDesc = data.returnParamsDesc;
            createForm.interfaceJsonReturn = data.jsonReturn;
            createForm.interfaceRequestHeader = data.requestHeader;
            createForm.interfaceResponseHeader = data.responseHeader;
            createForm.interfaceMethod = data.method;
        }
    );
}
// 清空表单中数据
const cleanForm = () => {
    createForm.interfaceName = '';
    createForm.interfaceDescription = '';
    createForm.interfaceUrl = '';
    createForm.interfacePath = '';
    createForm.interfaceRequestParams = '';
    createForm.interfaceRequestParamsDesc = '';
    createForm.interfaceReturnParamsDesc = '';
    createForm.interfaceJsonReturn = '';
    createForm.interfaceRequestHeader = '';
    createForm.interfaceResponseHeader = '';
    createForm.interfaceStatus = '';
    createForm.interfaceMethod = '';
}
// 关闭表单窗口时提示
const handleClose = () => {
    // 清空表单中的数据
    cleanForm();
}
// 格式化时间
const formatDate = (row, column, cellValue) => {
    if (cellValue) {
        return cellValue.substring(0, 10); // 返回前10个字符，即"yyyy-MM-dd"的格式
    }
    return "";
}
// 删除接口
const handleDelete = (index, row) => {
    ElMessageBox.confirm('确定要删除该接口吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(() => {
            post('/api/interfaceInfo/delete',
                {
                    id: row.id,
                },
                () => {
                    ElMessage({
                        message: "删除接口成功！",
                        type: "success",
                    })
                    // 刷新数据
                    loadData(currentPage, pageSize)
                    // 关闭表单窗口
                    addDialog.value = false;
                }
            );
        })
        .catch(() => {
            // 不关闭窗口
        })
}
// 搜索接口
const onSearch = (page) => {
    if (searchKeyword.interfaceId === "" && searchKeyword.interfaceName === "" ) {
        ElMessage({
            message: "请输入关键词！",
            type: "warning",
        })
    } else {
        post('/api/interfaceInfo/list/page',
            {
                id:  searchKeyword.interfaceId,
                name:  searchKeyword.interfaceName,
            },
            (data) => {
                dataList.value = data.records;
                total.value = data.total;
                currentPage.value = page.value // 更新当前页码
                dataList.value.forEach((item) => {
                    item.returnParamsDesc = JSON.parse(item.returnParamsDesc.replace(/[\r|\n|\t]/g,""))
                    item.requestParamsDesc = JSON.parse(item.requestParamsDesc.replace(/[\r|\n|\t]/g,""))
                })
            }
        );
    }
};
// 重置表格数据
const resetData = (page) => {
    // 清空搜索框中数据
    searchKeyword.interfaceId = '';
    searchKeyword.interfaceName = '';
    // 调用后端接口获取数据
    loadData(page, pageSize.value)
}
// 获取行键
const getRowKeys = (row) => {
    //唯一标识id，也可以是你自己数据源中的其他某个代表唯一的字段
    return row.id
}
// 状态变化触发
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
// 页数变化时
const handleCurrentPageChange = (page) => {
    currentPage.value = page;
    // 调用后端接口获取数据
    loadData(page, pageSize.value)
}
// 从后端获取数据
const loadData = (page, pageSize) => {
    post('/api/interfaceInfo/list/page/',
        {
            current: currentPage.value,
            pageSize: pageSize.value
        },
        (data) => {
            dataList.value = data.records;
            total.value = data.total;
            dataList.value.forEach((item) => {
                if(item.status === 1) {
                    item.status = true
                } else {
                    item.status = false
                }
                item.returnParamsDesc = JSON.parse(item.returnParamsDesc.replace(/[\r|\n|\t]/g,""))
                item.requestParamsDesc = JSON.parse(item.requestParamsDesc.replace(/[\r|\n|\t]/g,""))
            })
        }
    );
};

onMounted(() => {
    // 初始化加载数据
    loadData(currentPage, pageSize)
});
</script>

<template>
    <!--搜索框-->
    <div class="searchBox">
        <el-form :inline="true" :model="searchKeyword" size="large">
            <el-form-item style="margin: 0 10px">
                <span class="searchTitle">接口ID</span>
                <el-input v-model="searchKeyword.interfaceId" placeholder="请输入接口名称" clearable style="width: 150px;"/>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <span class="searchTitle">接口名称</span>
                <el-input v-model="searchKeyword.interfaceName" placeholder="请输入接口名称" clearable style="width: 150px;"/>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <el-button type="success" :icon="Refresh" @click="resetData">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <!--表格板块-->
    <div class="tableBlock">
        <div class="operateBox">
            <div class="OperationButton" >
                <el-button type="success" :icon="Plus" class="button" @click="addDialog=true">新增</el-button>
            </div>
        </div>
        <div id="showTable">
            <!--表格-->
            <el-table
                :row-key="getRowKeys"
                @selection-change="handleSelectionChange"
                :data="dataList"
                style="font-family: shangshou;font-size: 17px;font-weight: bold"
                :default-sort="{ prop: 'createTime', order: 'asc' }" border>
                <el-table-column type="expand">
                    <template #default="props">
                        <div m="4">
                            <p style="margin-left: 20px">描述:</p>
                            <p style="margin-left: 20px;margin-top: 20px;color: #67C23A">{{ props.row.description }}</p>

                            <p style="margin-left: 20px;margin-top: 20px">请求头:</p>
                            <el-tag style="font-size: 17px;margin: 20px" v-text="props.row.requestHeader" type="primary"></el-tag>

                            <p style="margin-left: 20px;margin-top: 20px">响应头:</p>
                            <el-tag style="font-size: 17px;margin: 20px" v-text="props.row.responseHeader" type="primary"></el-tag>

                            <p style="margin-left: 20px;margin-top: 20px">请求参数:</p>
                            <el-input class="expandInput" :rows="5" :autosize="{ minRows: 2, maxRows: 20 }"
                                      spellcheck="false"
                                      v-model="props.row.requestParams"
                                      disabled
                                      type="textarea"/>

                            <p style="margin-left: 20px;margin-top: 20px">参数说明: </p>
                            <el-table class="expandInput" :data="props.row.requestParamsDesc" border stripe>
                                <el-table-column prop="parameter" label="参数名" width="150" />
                                <el-table-column prop="type" label="类型" width="100" />
                                <el-table-column prop="description" label="说明"/>
                            </el-table>

                            <p style="margin-left: 20px;margin-top: 20px">返回参数说明: </p>
                            <el-table class="expandInput" :data="props.row.returnParamsDesc" border stripe>
                                <el-table-column prop="parameter" label="参数名" width="150" />
                                <el-table-column prop="type" label="类型" width="100" />
                                <el-table-column prop="description" label="说明"/>
                            </el-table>

                            <p style="margin-left: 20px;margin-top: 20px">JSON返回实例:</p>
                            <el-input class="expandInput" :rows="5" :autosize="{ minRows: 2, maxRows: 20 }"
                                      spellcheck="false"
                                      v-model="props.row.jsonReturn"
                                      disabled
                                      type="textarea"/>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="ID" width="50" prop="id"/>
                <el-table-column label="接口名称" width="200" prop="name"/>
                <el-table-column label="接口URL" width="200" prop="url"/>
                <el-table-column label="接口路径" width="200" prop="path"/>
                <el-table-column label="调用方法" width="85" prop="mehtod">
                    <template #default="scope">
                        <el-tag v-if="scope.row.method === 'GET'" type="success" style="width: 50px">GET</el-tag>
                        <el-tag v-if="scope.row.method === 'POST'" type="warning" style="width: 50px">POST</el-tag>
                        <el-tag v-if="scope.row.method === 'PUT'" type="primary" style="width: 50px">PUT</el-tag>
                        <el-tag v-if="scope.row.method === 'PATCH'" type="danger" style="width: 50px">PATCH</el-tag>
                        <el-tag v-if="scope.row.method === 'DELETE'" type="info" style="width: 50px">DELETE</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="接口状态" width="85" prop="status">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.status"
                            inline-prompt
                            active-text="上线"
                            inactive-text=下线
                            @change="changeInterfaceStatus(scope.$index, scope.row)"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="120" prop="createTime" :formatter="formatDate" sortable >
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="primary" :icon="Edit"
                                   @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" :icon="Delete"
                                   @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页器-->
            <el-pagination
                background
                style="margin-top: 15px"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="total"
                @current-change="handleCurrentPageChange"
                layout="prev, pager, next, total"
            ></el-pagination>
        </div>
    </div>

    <!--新增接口信息表单-->
    <el-dialog v-model="addDialog" title="添加接口" width="40%" style="color: #909399" @close="handleClose">
        <el-form :model="createForm" :label-position="labelPosition" status-icon>
            <el-form-item label="接口名称" prop="interfaceName">
                <el-input v-model="createForm.interfaceName" placeholder="请输入接口名称" type="text"/>
            </el-form-item>
            <el-form-item label="接口描述" prop="interfaceDescription">
                <el-input v-model="createForm.interfaceDescription" placeholder="请输入接口描述" type="text"/>
            </el-form-item>
            <el-form-item label="接口Url" prop="interfaceUrl">
                <el-input v-model="createForm.interfaceUrl" placeholder="请输入接口Url" type="text"/>
            </el-form-item>
            <el-form-item label="接口路径" prop="interfacePath">
                <el-input v-model="createForm.interfacePath" placeholder="请输入接口路径" type="text"/>
            </el-form-item>
            <el-form-item label="接口请求参数" prop="interfaceRequestParams">
                <el-input v-model="createForm.interfaceRequestParams" placeholder="请输入接口请求参数" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="接口请求参数说明" prop="interfaceRequestParamsDesc">
                <el-input v-model="createForm.interfaceRequestParamsDesc" placeholder="请输入接口请求参数说明" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="接口返回参数说明" prop="interfaceReturnParamsDesc">
                <el-input v-model="createForm.interfaceReturnParamsDesc" placeholder="请输入接口返回参数说明" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="JSON示例" prop="interfaceJsonReturn">
                <el-input v-model="createForm.interfaceJsonReturn" placeholder="JSON示例" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="请求头" prop="userName">
                <el-input v-model="createForm.interfaceRequestHeader" placeholder="请输入请求头" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="响应头" prop="userName">
                <el-input v-model="createForm.interfaceResponseHeader" placeholder="请输入响应头" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="请求方法" prop="userName">
                <el-select v-model="createForm.interfaceMethod" placeholder="请选择请求方法" >
                    <el-option label="GET" value="GET"/>
                    <el-option label="POST" value="POST"/>
                    <el-option label="PUT" value="PUT"/>
                    <el-option label="PATCH" value="PATCH"/>
                    <el-option label="DELETE" value="DELETE"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="danger" @click="dialogClose" class="button">取消</el-button>
            <el-button type="success" @click="handleAddConfirm" class="button">确认</el-button>
        </template>
    </el-dialog>
    <!--编辑接口信息表单-->
    <el-dialog v-model="editDialog" title="编辑接口" width="40%" style="color: #909399" @close="handleClose">
        <el-form :model="createForm" :label-position="labelPosition" status-icon>
            <el-form-item label="接口名称" prop="interfaceName">
                <el-input v-model="createForm.interfaceName" placeholder="请输入接口名称" type="text"/>
            </el-form-item>
            <el-form-item label="接口描述" prop="interfaceDescription">
                <el-input v-model="createForm.interfaceDescription" placeholder="请输入接口描述" type="text"/>
            </el-form-item>
            <el-form-item label="接口Url" prop="interfaceUrl">
                <el-input v-model="createForm.interfaceUrl" placeholder="请输入接口Url" type="text"/>
            </el-form-item>
            <el-form-item label="接口路径" prop="interfacePath">
                <el-input v-model="createForm.interfacePath" placeholder="请输入接口路径" type="text"/>
            </el-form-item>
            <el-form-item label="接口请求参数" prop="interfaceRequestParams">
                <el-input v-model="createForm.interfaceRequestParams" placeholder="请输入接口请求参数" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="接口请求参数说明" prop="interfaceRequestParamsDesc">
                <el-input v-model="createForm.interfaceRequestParamsDesc" placeholder="请输入接口请求参数说明" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="接口返回参数说明" prop="interfaceReturnParamsDesc">
                <el-input v-model="createForm.interfaceReturnParamsDesc" placeholder="请输入接口返回参数说明" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="JSON示例" prop="interfaceJsonReturn">
                <el-input v-model="createForm.interfaceJsonReturn" placeholder="JSON示例" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="请求头" prop="userName">
                <el-input v-model="createForm.interfaceRequestHeader" placeholder="请输入请求头" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="响应头" prop="userName">
                <el-input v-model="createForm.interfaceResponseHeader" placeholder="请输入响应头" type="textarea" :autosize="{ minRows: 5, maxRows: 20 }"/>
            </el-form-item>
            <el-form-item label="请求方法" prop="userName">
                <el-select v-model="createForm.interfaceMethod" placeholder="请选择请求方法" >
                    <el-option label="GET" value="GET"/>
                    <el-option label="POST" value="POST"/>
                    <el-option label="PUT" value="PUT"/>
                    <el-option label="PATCH" value="PATCH"/>
                    <el-option label="DELETE" value="DELETE"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="danger" @click="dialogClose" class="button">取消</el-button>
            <el-button type="success" @click="handleEditConfirm" class="button">确认</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
@font-face {
    font-family: "Sphere fez"; /* 定义字体名称 */
    src: url('/src/assets/font/spherefez-ezxam.ttf') format('truetype'); /* 指定字体文件的路径和格式 */
}

@font-face {
    font-family: "shangshou"; /* 定义字体名称 */
    src: url('/src/assets/font/上首简黑极细体.ttf') format('truetype'); /* 指定字体文件的路径和格式 */
}

.searchTitle {
    color:#909399;
    font-size: 20px;
    margin-right: 10px;
    font-weight: bold;
    font-family: shangshou;
}

.expandInput {
    width: 60%;
    margin: 20px;
    font-size: 15px;
    font-family: Arial;
}
</style>